package com.oa.modules.approvalsec1.controller;

import java.io.IOException;
import java.util.*;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.oa.common.utils.AppUtils;
import com.oa.common.utils.SmsUtil;
import com.oa.modules.approvalsec1.entity.ExplorationCloudEntity;
import com.oa.modules.approvalsec1.service.ExplorationCloudService;
import com.oa.modules.approvalsec1.service.NewsNoticeService;
import com.oa.modules.approvalsec1.service.RoomStoreService;
import com.oa.modules.approvalsec1.socket.WebSocketServer;
import com.oa.modules.sys.controller.AbstractController;
import com.oa.modules.sys.entity.SysUserEntity;
import com.oa.modules.sys.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import com.oa.common.utils.PageUtils;
import com.oa.common.utils.R;

import com.oa.modules.approvalsec1.entity.RoomStoreEntity;


/**
 * 存放房间表
 *
 * @author jiangwei
 * @email 785297226@qq.com
 * @date 2021-04-06 14:12:59
 */
@RestController
@RequestMapping("room/store")
@Api(tags = "存放房间表相关接口")
public class RoomStoreController extends AbstractController {
    @Autowired
    private RoomStoreService roomStoreService;

    @Autowired
    private SysUserService userService;

    @Autowired
    private ExplorationCloudService explorationCloudService;

    @Autowired
    private NewsNoticeService newsNoticeService;


    //天地图tk
    private static final String TIANDITU_GEOCONV_KEY = "3ee7246bbe83f328dec72925118c59f0";

    /**
     * 通过经纬度获取地址
     *
     * @return
     */
    public static Map<String, String> getArea(String lng, String lat) throws IOException {
        Map<String, String> area = new HashMap<>();
        String queryStr = "http://api.tianditu.gov.cn/geocoder?postStr={'lon':" + lng + ",'lat':" + lat + ",'ver':1}&type=geocode&tk=" + TIANDITU_GEOCONV_KEY;
//        URL编码{,}
        queryStr = queryStr.replace("}", "%7D");
        queryStr = queryStr.replace("{", "%7B");
//        获取http客户端
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(queryStr);
//        模拟浏览器
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3");
        CloseableHttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String returnResults = EntityUtils.toString(entity, "UTF-8");
            System.out.println(returnResults);
            JSONObject jsonObject = JSON.parseObject(returnResults);
            String result = jsonObject.get("result").toString();
            JSONObject jsonObjectResult = JSONObject.parseObject(result);
            String address = jsonObjectResult.get("addressComponent").toString();
            JSONObject jsonObjectAddress = JSONObject.parseObject(address);
            area.put("poi", jsonObjectAddress.get("poi").toString());
            area.put("lat", lat);
            area.put("lng", lng);
            area.put("address", jsonObjectAddress.get("address").toString());
            area.put("nation", jsonObjectAddress.get("nation").toString());
            area.put("province", jsonObjectAddress.get("province").toString());
            area.put("city", jsonObjectAddress.get("city").toString());
            area.put("county", jsonObjectAddress.get("county").toString());
        }
        response.close();
        return area;
    }

    @Test
    public void test() throws IOException {
        Map<String, String> area = getArea("116.609375", "36.591769");
        System.out.println(area);
    }

    /**
     * 列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "列表")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = roomStoreService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation(value = "信息")
    public R info(@PathVariable("id") String id) {
        RoomStoreEntity roomStore = roomStoreService.getById(id);
        return R.ok().put("roomStore", roomStore);
    }

    /**
     * 呼叫
     */
    @PostMapping("/save")
    @ApiOperation(value = "呼叫")
    public R save(@RequestBody RoomStoreEntity roomStore) {
        if (StringUtils.isBlank(roomStore.getRoomNum()) && StringUtils.isBlank(roomStore.getExplorationCloudId())) {
            return R.error("缺失必传参数roomNum或者explorationCloudId");
        }
        List<RoomStoreEntity> room = roomStoreService.list(new QueryWrapper<RoomStoreEntity>().eq("EXPLORATION_CLOUD_ID", roomStore.getExplorationCloudId()).orderByDesc("NUM_TIMES"));
        int numTimes = 1;
        if (room.size() != 0) {
            numTimes = room.get(0).getNumTimes() + 1;
        }
        String id = AppUtils.getUUID();
        roomStore.setId(id);
        roomStore.setNumTimes(numTimes);
        roomStore.setCreateDate(new Date());
        roomStore.setUserId(getUserId().toString());
        roomStore.setCreateOper(getUserId().toString());
        roomStoreService.save(roomStore);
        ExplorationCloudEntity explorationCloud = explorationCloudService.getById(roomStore.getExplorationCloudId());
        if (explorationCloud != null) {
            explorationCloud.setRoomNum(roomStore.getRoomNum());
            explorationCloudService.updateById(explorationCloud);
        }
        SysUserEntity userEntity = sysUserService.getById(roomStore.getPushId());
        if (null != userEntity || null != userEntity.getWxOpenId()) {
            String response = "";

            if (explorationCloud != null && explorationCloud.getIsAsd() == 1 && roomStore.getCallNumber() != null) {
                String msg = "齐河审批局邀请您加入视频会议，房间号：" + roomStore.getRoomNum() + " ,请前往爱山东-e齐办应用进入会议";
                Map req = SmsUtil.sendSms(roomStore.getCallNumber(), msg);
                if (Convert.toBool(req.get("success"))) {
                    return R.ok("呼叫成功");
                } else {
                    return R.error("呼叫失败,错误信息：" + req.toString());
                }
            } else if (explorationCloud.getIsAsd() == 0) {
               if (roomStore.getCallNumber() != null) {
                    response = WxLoginController.callPush(userEntity.getWxOpenId(), roomStore.getRoomNum(), roomStore.getCallNumber());
                } else {
                    response = WxLoginController.callPush(userEntity.getWxOpenId(), roomStore.getRoomNum(), "");
                }
                JSONObject jsonObject = JSON.parseObject(response);
                if (jsonObject.get("errcode").equals("0")) {
                    return R.ok("呼叫成功");
                } else {
                    return R.error("呼叫失败,错误信息：" + response);
                }
            }

        }
        return R.error("该用户暂未登录过微信小程序");
    }

    /**
     * 呼叫测试
     */
    @GetMapping("/callPushTest")
    public R callPushTest(String openid, String roomNum, String cloudId) {
        String response = WxLoginController.callPush(openid, roomNum, cloudId);
        JSONObject jsonObject = JSON.parseObject(response);
        if (jsonObject.get("errcode").equals(0) || jsonObject.get("errcode").equals("0")) {
            return R.ok("呼叫成功");
        } else {
            return R.error("呼叫失败,错误信息：" + response);
        }
    }

    /**
     * 通知测试
     */
    @GetMapping("/noticePushTest")
    public R pushTest(String openid) {
        String response = WxLoginController.noticePush(openid, "帮办", "待分派", new Date(), new Date());
        JSONObject jsonObject = JSON.parseObject(response);
        if (jsonObject.get("errcode").equals(0) || jsonObject.get("errcode").equals("0")) {
            return R.ok("通知发送成功");
        } else {
            return R.error("通知发送失败,错误信息：" + response);
        }
    }

    /**
     * 开户测试
     */
    @GetMapping("/OpenAccountPushTest")
    public R OpenAccountPushTest(String openid) {
        String response = WxLoginController.OpenAccountPush(
                openid,
                "山东易路方舟信息科技有限公司",
                "测试人",
                "13838381438",
                "370502MAFSWE153242",
                "山东省济南市高新区鑫盛大厦"
        );
        JSONObject jsonObject = JSON.parseObject(response);
        if (jsonObject.get("errcode").equals(0) || jsonObject.get("errcode").equals("0")) {
            return R.ok("开户发送成功");
        } else {
            return R.error("开户发送失败,错误信息：" + response);
        }
    }

    /**
     * 挂断
     */
    @PostMapping("/delete")
    @ApiOperation(value = "挂断")
    public R delete(@RequestBody RoomStoreEntity roomStore) {
        if (StringUtils.isBlank(roomStore.getRoomNum()) && StringUtils.isBlank(roomStore.getUserId()) && StringUtils.isBlank(roomStore.getExplorationCloudId())) {
            return R.error("请填写必要参数房间号和申请人用户id和列表id");
        }
        RoomStoreEntity room = roomStoreService.queryByRoom(roomStore.getRoomNum());
        if (null != room && room.getStatus() == 0) {
            ExplorationCloudEntity explorationCloud = new ExplorationCloudEntity();
            explorationCloud.setId(roomStore.getExplorationCloudId());
            explorationCloud.setIsHandler(roomStore.getIsHandler());
            explorationCloudService.updateById(explorationCloud);
            room.setStatus(1);
            roomStoreService.updateById(room);
            return R.ok();
        } else {
            return R.error("房间已销毁");
        }

    }

    /**
     * 接听
     */
    @PostMapping("/answerCall")
    @ApiOperation(value = "接听")
    public R answerCall(@RequestBody RoomStoreEntity roomStore) {
        if (StringUtils.isBlank(roomStore.getRoomNum())) {
            return R.error("请填写必要参数房间号");
        }
        SysUserEntity user = userService.getById(roomStore.getUserId());
        SysUserEntity user2 = userService.getById(roomStore.getPushId());
        if (user != null && user.getIsConversations().equals("0")) {
            return R.error("邀请人" + user.getUsername() + "正在通话中！");
        }
        if (user2 != null && user2.getIsConversations().equals("0")) {
            return R.error("被邀请人" + user2.getUsername() + "正在通话中！");
        }
        if (user != null) {
            user.setIsConversations("1");
            userService.updateById(user);
        } else {
            return R.error("邀请人不存在，请联系管理员！");
        }
        if (user2 != null) {
            user2.setIsConversations("1");
            userService.updateById(user2);
        } else {
            return R.error("被邀请人不存在，请联系管理员！");
        }
        //查询出被邀请人用户的房间。
        RoomStoreEntity room = roomStoreService.queryByRoom(roomStore.getRoomNum());
        if (null != room) {
            return R.ok();
        } else {
            return R.error("房间已销毁");
        }

    }

    /**
     * 通过经纬度获取位置
     */
    @PostMapping("/getArea")
    @ApiOperation(value = "通过经纬度获取位置")
    public R getArea(@RequestBody RoomStoreEntity roomStore) throws IOException {
        Map<String, String> map = getArea(roomStore.getLng(), roomStore.getLat());
        if (roomStore.getRoomNum() != null) {
            RoomStoreEntity roomStoreEntities = roomStoreService.queryByRoom(roomStore.getRoomNum());
            List<RoomStoreEntity> roomStoreEntities2 = roomStoreService.list(new QueryWrapper<RoomStoreEntity>().eq("EXPLORATION_CLOUD_ID", roomStore.getExplorationCloudId()).eq("LNG", null));
            //默认是最多只有1条控的。
            if (roomStoreEntities2.size() != 0) {
                roomStoreEntities.setNumTimes(roomStoreEntities2.get(0).getNumTimes());
                roomStoreService.removeById(roomStoreEntities2.get(0).getId());
            }
            roomStoreEntities.setLat(roomStore.getLat());
            roomStoreEntities.setLng(roomStore.getLng());
            roomStoreEntities.setAddress(map.get("address"));
            roomStoreService.updateById(roomStoreEntities);
            try {
                if (roomStoreEntities != null) {
                    WebSocketServer.sendInfo2(map.get("address"), roomStoreEntities.getUserId());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return R.ok().put("data", map);
        } else {
            return R.error("没有房间号");
        }
    }

}
